package cn.zyb.system.service.impl;

import cn.zyb.basic.service.Impl.BaseServiceImpl;
import cn.zyb.system.domain.Role;
import cn.zyb.system.mapper.RoleMapper;
import cn.zyb.system.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 业务实现类：
 */
@Service
public class RoleServiceImpl extends BaseServiceImpl<Role> implements IRoleService {

  @Autowired
  private RoleMapper roleMapper;

  @Override
  @Transactional
  public void add(Role role) {
    super.add(role);
    addRoleMenuAndPermission(role);
  }

  @Override
  @Transactional
  public void del(Long id) {//role_id
    //删除角色菜单中间表
    roleMapper.delMenuByRoleId(id);
    //删除角色权限中间表
    roleMapper.delPermissionByRoleId(id);
    //删除员工角色中间表
    roleMapper.delEmployeeRoleByRoleId(id);
    //删除的时候有外键关联 - 所以先删除中间表数据再删除主表数据
    super.del(id);
  }

  @Override
  @Transactional
  public void update(Role role) {
    super.update(role);

    //先删除旧的权限和菜单
    //删除角色菜单中间表
    roleMapper.delMenuByRoleId(role.getId());
    //删除角色权限中间表
    roleMapper.delPermissionByRoleId(role.getId());

    addRoleMenuAndPermission(role);
  }


  public void addRoleMenuAndPermission(Role role){
    List<Long> menus = role.getMenus();
    if(menus.size()>0){//当前角色选择了菜单
      roleMapper.addRoleMenu(role);
    }
    List<Long> permissions = role.getPermissions();
    if(permissions.size()>0){//当前选择寻找了菜单
      roleMapper.addRolePermission(role);
    }
  }

}
